package com.techwells.learningkites.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.R.integer;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.lidroid.xutils.BitmapUtils;
import com.techwells.learningkites.R;
import com.techwells.learningkites.R.layout;
import com.techwells.learningkites.cache.UserCenter;
import com.techwells.learningkites.model.LoginViewModel;
import com.techwells.learningkites.model.SettingUserinfoViewModel;
import com.techwells.learningkites.networkaccess.KitesRequestUrl;
import com.techwells.learningkites.networkservice.KitesServiceMediator;
import com.techwells.learningkites.networkservice.model.User;
import com.techwells.learningkites.networkservice.model.UserProfile;
import com.techwells.taco.base.CommonBaseActivity;
import com.techwells.taco.mvvm.Route;
import com.techwells.taco.networkservice.ServiceMediator;
import com.techwells.taco.tasktool.TaskToken;
import com.techwells.taco.utils.Base64Coder;
import com.techwells.taco.utils.CommonUtil;
import com.techwells.taco.utils.ToastUtils;

public class SettingUserInfoActivity extends CommonBaseActivity implements
		OnClickListener {

	private TextView titleRight;
	private com.techwells.taco.widget.RoundImageView userIcon;
	private TextView userName, sex;
	private EditText nickname, name, address, mail, mobile;
	private LinearLayout llSex;
	private String[] sexString = { "男", "女" };

	private SettingUserinfoViewModel presentModel;
	private int gender = 1;
	private String avatar;
	private BitmapUtils bitmapUtils;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting_user_info);

		initTitleBar(getResources().getString(R.string.setting_userinfo),
				defaultLeftClickListener, this, R.drawable.g_icon_back, 0);
		bitmapUtils = new BitmapUtils(this);
		initViews();
	}

	private void initViews() {
		titleRight = (TextView) findViewById(R.id.common_activity_title_right_tv);
		titleRight.setText(getResources().getString(R.string.save));
		titleRight.setVisibility(View.VISIBLE);

		userIcon = (com.techwells.taco.widget.RoundImageView) findViewById(R.id.user_icon);
		userIcon.setOnClickListener(this);
		userName = (TextView) findViewById(R.id.username);

		nickname = (EditText) findViewById(R.id.nickname);
		name = (EditText) findViewById(R.id.name);
		sex = (TextView) findViewById(R.id.sex);
		address = (EditText) findViewById(R.id.address);
		mail = (EditText) findViewById(R.id.mail);
		mobile = (EditText) findViewById(R.id.mobile);

		llSex = (LinearLayout) findViewById(R.id.ll_select_sex);
		llSex.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.common_activity_title_right_tv:
			// Route.route().nextController(SettingUserInfo.this,
			// MainPageActivity.class.getName(), Route.WITHOUT_RESULTCODE);
			if (UserCenter.getInstance().getUser() != null) {
				doRequestBasic();
			}

			break;
		case R.id.ll_select_sex:
			gender = 1;
			View sexView = LayoutInflater.from(this).inflate(
					R.layout.gender_picker, null);
			NumberPicker sexPicker = (NumberPicker) sexView
					.findViewById(R.id.gender_picker);
			sexPicker.setDisplayedValues(sexString);
			sexPicker.setMinValue(0);
			sexPicker.setMaxValue(sexString.length - 1);
			sexPicker.setValue(0);
			sexPicker
					.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
			sexPicker.setOnValueChangedListener(new OnValueChangeListener() {

				@Override
				public void onValueChange(NumberPicker picker, int oldVal,
						int newVal) {
					switch (picker.getId()) {
					case R.id.gender_picker:
						if (newVal == 0) {
							gender = 1;
						} else if (gender == 1) {
							gender = 2;
						}
						break;

					default:
						break;
					}

				}
			});

			new AlertDialog.Builder(this)
					.setTitle("选择性别")
					.setView(sexView)
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									if (gender == 1) {
										sex.setText("男");
									} else if (gender == 2) {
										sex.setText("女");
									}

								}
							}).show();

			break;
		case R.id.user_icon:
			// doRequestGetAvatars();
			Route.route().nextController(SettingUserInfoActivity.this,
					ChooseUserAvatar.class.getName(), 1);
			break;

		default:
			break;
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		doRequestGetProfile();
	}

	@Override
	public void alreadyBindBaseViewModel() {
		// TODO Auto-generated method stub
		super.alreadyBindBaseViewModel();
		presentModel = (SettingUserinfoViewModel) baseViewModel;

	}

	private void doRequestGetAvatars() {
		doTask(KitesServiceMediator.SERVICE_GET_AVATARS, null);
	}

	private void doRequestBasic() {
		HashMap<String, Object> argMap = new HashMap<String, Object>();
		argMap.put("uid", UserCenter.getInstance().getUser().id);
		argMap.put("nickName", nickname.getText().toString());
		argMap.put("name", name.getText().toString());
		argMap.put("gender", gender);
		argMap.put("address", address.getText().toString());
		argMap.put("email", mail.getText().toString());
		argMap.put("mobile", mobile.getText().toString());
		if (avatar != null && !avatar.equals("")) {
			argMap.put("avatar", avatar);
		}else {
			argMap.put("avatar", UserCenter.getInstance().getUser().avatar);
		}
		doTask(KitesServiceMediator.SERVICE_DO_BASIC, argMap);

	}

	private void doRequestGetProfile() {
		doTask(KitesServiceMediator.SERVICE_GET_PROFILE, null);

	}

	@Override
	public void refreshData(TaskToken token) {
		// TODO Auto-generated method stub
		super.refreshData(token);

		String method = token.method;
		if (method.equals(KitesServiceMediator.SERVICE_GET_PROFILE)) {
			UserProfile userProfile = ((SettingUserinfoViewModel) baseViewModel).userProfile;
			UserCenter.getInstance().setUser(userProfile.user);
			
			
			
			if (userProfile.user.nickName != null) {
				nickname.setText(userProfile.user.nickName);
			}
			if (userProfile.user.name != null) {
				name.setText(userProfile.user.name);
			}
			if (avatar != null && !avatar.equals("")) {
				bitmapUtils.display(userIcon, KitesRequestUrl.BASE_URL_IMG + avatar);
			}else if (userProfile.user.avatar != null) {
				int index = userProfile.user.avatar.indexOf(".");
				if (index != -1) {
					String avatarUrlCheck = userProfile.user.avatar.substring(index + 1);
					if (avatarUrlCheck.equals("gif")) {
						bitmapUtils.display(userIcon, KitesRequestUrl.BASE_URL_IMG + userProfile.user.avatar);
					}
				}else {
					userIcon.setBackgroundColor(getResources().getColor(R.color.white_1));
				}
			}else if (userProfile.user.avatar == null) {
				userIcon.setBackgroundColor(getResources().getColor(R.color.white_1));
			}
			
			
			
			if (userProfile.user.mobile != null) {
				mobile.setText(userProfile.user.mobile);
			}
			if (userProfile.user.email != null) {
				mail.setText(userProfile.user.email);
			}
			if (userProfile.user.gender > 0 && userProfile.user.gender < 4) {
				switch (userProfile.user.gender) {
				case 1:
					sex.setText("男");
					break;
				case 2:
					sex.setText("女");
					break;
				case 3:
					sex.setText("未知");
					break;

				default:
					break;
				}
			}
			if (userProfile.user.address != null) {
				address.setText(userProfile.user.address);
			}
			
		} else if (method.equals(KitesServiceMediator.SERVICE_DO_BASIC)) {
			int basicReturnCode = ((SettingUserinfoViewModel) baseViewModel).basicReturnCode;
			if (basicReturnCode == ServiceMediator.Service_Return_Success) {
				ToastUtils.show(this, "个人信息修改成功");
				Route.route().nextController(this,
						MainPageActivity.class.getName(),
						Route.WITHOUT_RESULTCODE);
			}
		}

	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		avatar = data.getStringExtra("avatar");
		if (avatar != null && !avatar.equals("")) {
			bitmapUtils.display(userIcon, KitesRequestUrl.BASE_URL_IMG + avatar);
		}
		
	}

}
